package com.wyu.notaryserver.service.impl;

import ch.qos.logback.classic.Logger;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyu.notaryserver.domain.*;
import com.wyu.notaryserver.exception.BizException;
import com.wyu.notaryserver.mapper.CaseClientMapper;
import com.wyu.notaryserver.mapper.ClientMapper;
import com.wyu.notaryserver.mapper.PictureMapper;
import com.wyu.notaryserver.service.OcrService;
import com.wyu.notaryserver.util.AliOSSUtil;
import com.wyu.notaryserver.util.Base64MultipartFile;
import com.wyu.notaryserver.util.OCR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 针对 OCR 服务的实现类
 */
@Service
@Slf4j
public class OcrServiceImpl implements OcrService {
    @Autowired
    private OCR ocr;

    @Autowired
    private CaseClientMapper caseClientMapper;

    @Autowired
    private AliOSSUtil aliOSSUtil;

    @Autowired
    private PictureMapper pictureMapper;

    @Override
    public List<CommonDTO> fileUpload(String[] files,List<String> uuidList,String licenseName) throws IOException{
        List<CommonDTO> commonDTOList = new ArrayList<>();
        //图片类型为身份证
        if(licenseName.equals("身份证")){
            for (int i = 0; i < uuidList.size(); i++) {
                CommonDTO idCardDTO = new CommonDTO();
                idCardDTO.setUuid(uuidList.get(i));
                commonDTOList.add(idCardDTO);
            }
        }
        //图片类型为护照
        if(licenseName.equals("护照")){
            for (int i = 0; i < uuidList.size(); i++) {
                CommonDTO passportDTO = new CommonDTO();
                passportDTO.setUuid(uuidList.get(i));
                commonDTOList.add(passportDTO);
            }
        }

        //转集合(调用OCR接口)
        List<String> imageList = new ArrayList<>();
        for (String image : files) {
            imageList.add(image);
        }

        //todo 明确案例
        //调用OCR接口
        OcrImageDTO ocrImageDTO = ocr.getImageText(imageList);

        //身份证字段解析
        if(licenseName.equals("身份证")) {
            for (int i = 0; i < uuidList.size(); i++) {
                //创建身份证DTO的info
                List<Map<String, String>> idCardInfoList = new ArrayList<>();
                //身份证字段解析
                idCardParse(ocrImageDTO, idCardInfoList);
                commonDTOList.get(i).setInfo(idCardInfoList);
            }

        }
            //  护照字段解析
        if(licenseName.equals("护照")) {
            for (int i = 0; i < uuidList.size(); i++) {
                //创建护照DTO的info
                List<Map<String, String>> passportInfoList = new ArrayList<>();
                //护照字段解析
                passportParse(ocrImageDTO, passportInfoList);
                commonDTOList.get(i).setInfo(passportInfoList);
            }

        }
            return commonDTOList;
    }

    /**
     * 保存到数据库
     * @param clientDTO
     *//*
    @Override
    public void fileSave(ClientDTO clientDTO) {
        //保存到用户表
        ClientDO clientDO = new ClientDO();
        clientDO.setName(clientDTO.getName());
        clientDO.setGender(clientDTO.getGender());
        clientDO.setBirthdate(clientDTO.getBirthdate());
        clientDO.setAddress(clientDTO.getAddress());
        clientDO.setIdcardNumber(clientDTO.getIdcardNumber());
        clientMapper.insert(clientDO);
        //保存到照片表
        PictureDO pictureDO = new PictureDO();
        //存储护照
        if (clientDTO.getPassport() != null){
            pictureDO.setTypeId(2);
            pictureDO.setTypeName("护照");
            pictureDO.setUrl(clientDTO.getPassport());
            pictureMapper.insert(pictureDO);
        }
        //存储身份证
        if (clientDTO.getIdcard() != null){
            pictureDO.setTypeId(1);
            pictureDO.setTypeName("身份证");
            pictureDO.setUrl(clientDTO.getIdcard());
            pictureMapper.insert(pictureDO);
        }
    }*/

    /**
     * 获取模板
     * @return
     */
    @Override
    public MouldVO getMould(String user_token) {
        MouldVO mouldVO = new MouldVO();
        /*QueryWrapper queryWrapper = new QueryWrapper<>();

        String userId =
        queryWrapper.eq("clientId",userId);
        ClientDO clientDO = clientMapper.select(user_token);*/
        //暂时写死
        mouldVO.setCaseId("60");
        Participants[] participants = new Participants[2];
        Participants participant = new Participants();
        participant.setName("姓名");
        participant.setNeed(1);
        participants[0] = participant;
        mouldVO.setParticipants(participants);
        return mouldVO;
    }

    /**
     ************************************************private method*****************************************************
     */

    /**
     * 将Base64编码的字符串转换为MultipartFile对象
     * @param base64Image Base64编码的图片字符串
     * @param fileName 文件名
     * @param contentType 内容类型（例如：image/jpeg）
     * @return MultipartFile对象
     * @throws IOException 如果文件操作发生错误
     */
    public static MultipartFile convertBase64ToMultipartFile(String base64Image, String fileName, String contentType) throws IOException {
        // 解码Base64字符串
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);

        // 创建MockMultipartFile对象
        return new Base64MultipartFile(imageBytes, fileName,fileName, contentType);
    }

    /**
     * 身份证字段解析
     * @param ocrImageDTO
     * @param idCardInfoList
     */
    private void idCardParse(OcrImageDTO ocrImageDTO, List<Map<String, String>> idCardInfoList){
        String[] idCardResult = ocrImageDTO.getIdCardResult();
        if (idCardResult.length != 0) {
            for (int i = 0; i < idCardResult.length; i++) {
                //字段填充
                String result = idCardResult[i];
                // 姓名
                if (result.contains("姓名")) {
                    String[] name = result.split("姓名");
                    if (name.length > 0) {
                        Map<String, String> idCardMap = new HashMap<>();
                        idCardMap.put("key", "姓名");
                        idCardMap.put("value", name[1]);
                        idCardInfoList.add(idCardMap);
                    } else {
                        throw new BizException("姓名字段解析失败，请重新拍照上传");
                    }
                }
                // 性别
                if (result.contains("性别")) {
                    String[] sex = result.split("性别");
                    if (sex.length > 0) {
                        if (sex[1].contains("男")) {
                            Map<String, String> idCardMap = new HashMap<>();
                            idCardMap.put("value", "男");
                            idCardMap.put("key", "性别");
                            idCardInfoList.add(idCardMap);
                        } else {
                            Map<String, String> idCardMap = new HashMap<>();
                            idCardMap.put("value", "女");
                            idCardMap.put("key", "性别");
                            idCardInfoList.add(idCardMap);
                        }
                    } else {
                        throw new BizException("性别字段解析失败，请重新拍照上传");
                    }
                }
                // 民族
                if (result.contains("民族")) {
                    String[] nation = result.split("民族");
                    if (nation.length > 1) {
                        Map<String, String> idCardMap = new HashMap<>();
                        idCardMap.put("value", nation[1]);
                        idCardMap.put("key", "民族");
                        idCardInfoList.add(idCardMap);
                    } else {
                        throw new BizException("民族字段解析失败，请重新拍照上传");
                    }
                }
                // 出生日期
                if (result.contains("出生")) {
                    String[] birthDate = result.split("出生");
                    if (birthDate.length > 1) {
                        String dateString = birthDate[1];
                        Map<String, String> idCardMap = new HashMap<>();
                        idCardMap.put("value", dateString);
                        idCardMap.put("key", "出生日期");
                        idCardInfoList.add(idCardMap);
                    }else {
                        int next = i + 1;
                        Map<String, String> idCardMap = new HashMap<>();
                        idCardMap.put("value", idCardResult[next]);
                        idCardMap.put("key", "出生日期");
                        idCardInfoList.add(idCardMap);
                    }

                }
                // 地址
                if (result.contains("址")) {
                    int flag = 0;
                    StringBuilder addressBuilder = new StringBuilder();
                    for (int j = 0; j < 99; j++) {
                        if (!idCardResult[i].contains("身份")) {
                            addressBuilder.append(idCardResult[i]);
                            i++;
                            flag++;
                        } else {
                            String address = addressBuilder.toString();
                            String[] trueAddress = address.split("住址");
                            Map<String, String> idCardMap = new HashMap<>();
                            idCardMap.put("value", trueAddress[1]);
                            idCardMap.put("key", "地址");
                            idCardInfoList.add(idCardMap);
                            i=i-flag;
                            break;
                        }
                    }
                }
                // 身份证号
                if (result.contains("身份")) {
                    String[] idCard = result.split("公民身份号码");
                    if (idCard.length > 0) {
                        Map<String, String> idCardMap = new HashMap<>();
                        idCardMap.put("value", idCard[1]);
                        idCardMap.put("key", "身份证号");
                        idCardInfoList.add(idCardMap);
                    } else {
                        int next = i + 1;
                        Map<String, String> idCardMap = new HashMap<>();
                        idCardMap.put("value", idCardResult[next]);
                        idCardMap.put("key", "身份证号");
                        idCardInfoList.add(idCardMap);
                    }
                }
            }
    }}

    /**
     * 护照字段解析
     * @param ocrImageDTO
     * @param passportInfoList
     */
    //todo 函数循环需要处理
    private void passportParse(OcrImageDTO ocrImageDTO, List<Map<String, String>> passportInfoList){
        String[] passportResult = ocrImageDTO.getPassportResult();
        if (passportResult.length != 0) {
            for (int i = 0; i < passportResult.length; i++) {
                int previous = i--;
                if (passportResult[i].contains("姓名")) {
                    Map<String, String> passportMap = new HashMap<>();
                    passportMap.put("value", passportResult[previous]);
                    passportMap.put("key", "护照");
                    passportInfoList.add(passportMap);
                }
            }
        }
    }
}
